<?php
	
class Admin_ProductController extends TN_Controller_Action_Admin
{
 public function init()
    {
    	parent::init();
    }
    /**
     * Listado de las categorias de los productos
     */
 	public function indexAction()
 	{
 	  $lang = Common_Translate::getLanguage();
 	  $categories = new Zend_Models_LangProductCategory();
  	  $this->view->categories = $categories->getCategoriesByLang($lang);
 	}
 	/**
 	 * Creacion de un nuevo producto
 	 */
 	public function newcategoryAction()
 	{
 		$form = $this->addCategoryForm();
 		$this->view->form = $form;	
 		$langs = new Zend_Models_Lang();
 		$this->view->langs = $langs->getEnabledLangs();
       
    	if (!$this->getRequest()->isPost())
     	{
       		return;
     	}
     	else
    	 {
    		if (!$form->isValid($_POST))
    	  	{
    	  	    $this->view->form = $form;
				return;
			}
			else
			{
				$values = $form->getValues();
				
				$pc = new Zend_Models_ProductCategory();
				$pc = $pc->createRow();
				$pc->enabled = $values['common']['enabled'];
				if ( $values['common']['image'] == NULL )
				{
				  $pc->image = '';
				}	
				else
				{
				  $upload = $form->common->image->getTransferAdapter(); 
				  $info = $upload->getFileInfo();
				  if (!$upload->receive())
				  {	
				    $messages = $upload->getMessages();
   					echo implode("\n", $messages);
   					exit;
				  }	
				  
				  $pc->image = $info['image']['name'];
				}
				$pc->save();
				$langs = new Zend_Models_Lang();
				$langs = $langs->getEnabledLangs();
				foreach( $langs as $l )
				{
				  $lpc = new Zend_Models_LangProductCategory();
				  $lpc = $lpc->createRow();
				  $lpc->id_category = $pc->id;
				  $lpc->lang = $l['prefix2'];
				  $lpc->title = $values[$l['prefix2']]['title_'.$l['prefix2']];
				  $lpc->description = $values[$l['prefix2']]['description_'.$l['prefix2']];
				  $lpc->save();
				}  
				
            	$this->_redirect("/admin/product");
 
			}
		}
 	}
 	
 	public function deletecategoryAction()
 	{
 	  $this->disableView();
      $request = $this->_request->getParams();
      $category = $request['category'];
      $lc = new Zend_Models_LangProductCategory();
      $lc->delete("id_category = '$category'"); 
      $c = new Zend_Models_ProductCategory();
      $c = $c->getCategoryById($category);
      $c->delete();
      $this->_redirect("/admin/product");
 	}
 
 	
 	private function addCategoryForm()
 	{
 	  $form = new Zend_Form();
 	  $form->setAction("/admin/product/newcategory")
 			->setMethod('post');
 	  $form->setAttrib("class", "jNice")->setAttrib('enctype', 'multipart/form-data'); 
 	  /**** Datos comunes a los idiomas ****/   	
 	  $common = new Zend_Form_SubForm();  
 	  $enabled = $common->createElement('checkbox','enabled');
 	  $enabled->setLabel('Activo:');
	  $common->addElement($enabled);	
	  $image =  new Zend_Form_Element_File('image');  
	  $image->setLabel('Imagen:');	
	  $image->addValidator('Extension', false, array('gif', 'jpg', 'png'))->addErrorMessage('Formato de imagen no valido');
	  $image->setDestination(str_replace("\\","/",dirname(dirname(dirname(dirname(dirname(__FILE__)))))).'/upload/category_product/');
	  $common->addElement($image);
 	  $form->addSubForms(array("common" => $common));
	  
      $langs = new Zend_Models_Lang();
	  $langs = $langs->getEnabledLangs();
	  foreach( $langs as $l)
	  {
	    $sub = new Zend_Form_SubForm();
	    $name = $sub->createElement("text","title_".$l['prefix2']);
		$name->setAttrib("class", "text-long");
 	   	$name->addValidator('NotEmpty')->setLabel($this->view->t->_('*Nombre:'))->setRequired(true);
		$name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
		$description = $sub->createElement("textarea","description_".$l['prefix2']);
		$description->setLabel($this->view->t->_('Descripcion:'));
		$description->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
		$sub->addElement($name);
		$sub->addElement($description);
		$form->addSubForms(array($l['prefix2'] => $sub));
	  }
	  $form->addElement('submit', 'add', array('label' => $this->view->t->_('Aceptar')));
      return $form;
 	
 	}
 	
 	private function editCategoryForm()
 	{
 		$form = new Zend_Form();
 		$form->setAction("/admin/product/editcategory")
 				->setMethod('post');
 		$form->setAttrib("class", "jNice");		
 		$request = $this->_request->getParams();
 	    $category = $request['category']; 		
 	    $pcategory = new Zend_Models_ProductCategory();
 	    $pcategory = $pcategory->getCategoryById($category);
 	    
 	    /**** Datos comunes a los idiomas ****/   	
 	    $common = new Zend_Form_SubForm();  
 	    $enabled = $common->createElement('checkbox','enabled');
 	    $enabled->setLabel('Activo:');
 	    $enabled->setValue($pcategory->enabled);
	    $common->addElement($enabled);	
	    $image =  new Zend_Form_Element_File('image');  
	    $image->addValidator('Extension', false, array('gif', 'jpg', 'png'))->addErrorMessage('Formato de imagen no valido');
	    $image->setDestination(str_replace("\\","/",dirname(dirname(dirname(dirname(dirname(__FILE__)))))).'/upload/category_product/');
	    $imageHidden = $form->createElement('hidden', 'imageHidden');
	    $imageHidden->setLabel('Imagen:');	
		$imageHidden->setValue($pcategory->image);
		$this->view->value = $pcategory->image;
		$common->addElement($imageHidden);
		$common->addElement($image);
 	    $form->addSubForms(array("common" => $common));
 	    $langs = new Zend_Models_Lang();
	    $langs = $langs->getEnabledLangs();
	    foreach( $langs as $l)
	    {
	      $sub = new Zend_Form_SubForm();
	      $langCategory = new Zend_Models_LangProductCategory();
	      $langCategory = $langCategory->getCategoryByKey($pcategory->id, $l['prefix2']);
	      $name = $sub->createElement("text","title_".$l['prefix2']);
		  $name->setAttrib("class", "text-long");
 	   	  $name->addValidator('NotEmpty')->setLabel($this->view->t->_('*Nombre:'))->setRequired(true);
		  $name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
		  $name->setValue($langCategory['title']);
		  $description = $sub->createElement("textarea","description_".$l['prefix2']);
		  $description->setLabel($this->view->t->_('Descripcion:'));
		  $description->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
		  $description->setValue($langCategory['description']);
		  $sub->addElement($name);
		  $sub->addElement($description);
		  $form->addSubForms(array($l['prefix2'] => $sub));
	    }
 	    $id = $form->createElement("hidden",'id_category');
		$id->setValue($category);
		$form->addElement($id);
		$form->addElement('submit', 'add', array('label' => $this->view->t->_('Aceptar')));
		return $form;
 }
 	
 	public function editcategoryAction()
	{
 		$form = $this->editCategoryForm();
 		$this->view->form = $form;	
   	    $langs = new Zend_Models_Lang();
 		$this->view->langs = $langs->getEnabledLangs();
 		if (!$this->getRequest()->isPost())
    	{
       		return;
     	}
     	else
     	{
    		if (!$form->isValid($_POST))
      		{
				$this->view->form = $form;
				return;
			}
			else
			{
			  $values = $form->getValues();
       		  $pc = new Zend_Models_ProductCategory();
			  $pc = $pc->getCategoryById($values['id_category']);
			  $pc->enabled = $values['common']['enabled'];
			  if ( $values['common']['image'] == NULL )
			  {
			    $pc->image = $values['common']['imageHidden'];
			  }	
			  else
			  {
				$upload = $form->common->image->getTransferAdapter(); 
				$info = $upload->getFileInfo();
				if (!$upload->receive())
				{	
				  $messages = $upload->getMessages();
   				  echo implode("\n", $messages);
   				  exit;
				}	
				  
				  $pc->image = $info['image']['name'];
				}
				$pc->save();
				$langs = new Zend_Models_Lang();
				$langs = $langs->getEnabledLangs();
				foreach( $langs as $l )
				{
				  $lpc = new Zend_Models_LangProductCategory();
				  $lpc = $lpc->getCategoryById($values['id_category'], $l['prefix2']);
				  if ( count( $lpc ) <= 0 )
				  {
                    $lpc = new Zend_Models_LangProductCategory();
				    $lpc = $lpc->createRow();
				  }  
				  $lpc->id_category = $pc->id;
				  $lpc->lang = $l['prefix2'];
				  $lpc->title = $values[$l['prefix2']]['title_'.$l['prefix2']];
				  $lpc->description = $values[$l['prefix2']]['description_'.$l['prefix2']];
				  $lpc->save();
				}  
			$this->_redirect("/admin/product");
 			}
		}
 	}
 	
 	public function listproductsAction()
 	{
 		$request = $this->_request->getParams();
   		$category = $request['category']; 
    	$this->view->category = $category;
    	$lang = Common_Translate::getLanguage();
    	$c = new Zend_Models_LangProductCategory();
    	$c = $c->getCategoryById($category,$lang);
   		$this->view->categoryName = $c->title;
   		$products = new Zend_Models_LangProduct();
 		$this->view->products = $products->getProductsByCategory($category,$lang);
 	}
 	/*
 	 * TODO: Imagen
 	 */
 	public function newproductAction()
 	{
	    $form = $this->addProductForm();
 		$this->view->form = $form;	
 		$langs = new Zend_Models_Lang();
 		$this->view->langs = $langs->getEnabledLangs();
 		if (!$this->getRequest()->isPost())
     	{
     	  	return;
     	}
     	else
    	{
    		if (!$form->isValid($_POST))
      		{
				$this->view->form = $form;
				return;
			}
			else
			{
				$values = $form->getValues();
				$product = new Zend_Models_Product();
				$product = $product->createRow();
				$product->enabled = $values['common']['enabled'];
				$product->hightlight = $values['common']['hightlight'];
				$product->id_category = $values['common']['category'];
				$product->price = $values['common']['price'];
				if ( $values['common']['image'] == NULL )
				{
				  $product->image = '';
				}	
				else
				{
				  $upload = $form->common->image->getTransferAdapter(); 
                  $info = $upload->getFileInfo();
				  if (!$upload->receive())
				  {	
				    $messages = $upload->getMessages();
   					echo implode("\n", $messages);
   					exit;
				  }	
					
					$product->image = $info['image']['name'];
				}
				$product->save();
				$langs = new Zend_Models_Lang();
				$langs = $langs->getEnabledLangs();
				foreach( $langs as $l )
				{
				  $lc = new Zend_Models_LangProduct();
				  $lc = $lc->createRow();
				  $lc->id_product = $product->id;
				  $lc->lang = $l['prefix2'];
				  $lc->title = $values[$l['prefix2']]['title_'.$l['prefix2']];
				  $lc->description = $values[$l['prefix2']]['description_'.$l['prefix2']];
				  $lc->save();
				} 
				$this->_redirect("/admin/product/listproducts/category/".$values['common']['category']);
			}
		}
	 }
	 /*
	  * TODO : Modificar con los campos del producto
	  */
	private function addProductForm()
	 {
		$form = new Zend_Form();
	 	$form->setAction("/admin/product/newproduct")
	             ->setMethod('post');
    	$form->setAttrib("class", "jNice");         
        $id_product = $this->_request->getParam('product');
        $lang = Common_Translate::getLanguage();
        $common = new Zend_Form_SubForm(); 
    	$category = $form->createElement("select","category");
		$categories = new Zend_Models_LangProductCategory();
		$categories = $categories->getCategoriesByLang($lang);	
		$category->setLabel('Categoría:');
		$category->addMultiOptions($this->formatCategories($categories)); 
 	    $enabled = $common->createElement('checkbox','enabled');
 	    $enabled->setLabel('Activo:');
 	    $hight = $common->createElement('checkbox','hightlight');
		$hight->setLabel('Destacado:');
		$cost = $common->createElement('text','price');
		$cost->setAttrib("class", "text-long");
		$cost->addValidator('Float')->setLabel('*Precio:')->setRequired(true);
		$cost->addErrorMessage('Valor real invalido');
 	    $image =  new Zend_Form_Element_File('image'); 
		$image->setLabel('Imagen:');	
		$image->addValidator('Extension', false, array('gif', 'jpg', 'png'))->addErrorMessage('Formato de imagen no valido');
		$image->setDestination(str_replace("\\","/",dirname(dirname(dirname(dirname(dirname(__FILE__)))))).'/upload/producto/');
 	    $common->addElement($category);
	    $common->addElement($enabled);
	    $common->addElement($hight);
	    $common->addElement($cost);
	    $common->addElement($image);	
	    $form->addSubForms(array("common" => $common));
        
	    $langs = new Zend_Models_Lang();
	    $langs = $langs->getEnabledLangs();
	    foreach( $langs as $l)
	    {
	      $sub = new Zend_Form_SubForm();
	      $name = $sub->createElement("text","title_".$l['prefix2']);
		  $name->setAttrib("class", "text-long");
 	   	  $name->addValidator('NotEmpty')->setLabel($this->view->t->_('*Titulo:'))->setRequired(true);
		  $name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
		  $sub->addElement($name);
		  $description = $sub->createElement("textarea", "description_".$l['prefix2']);
		  $description->setAttrib("class","mceAdvanced");
		  $description->setLabel($this->view->t->_('Descripcion:'));
		  $sub->addElement($description);
		  $form->addSubForms(array($l['prefix2'] => $sub));
	    }
   		$form->addElement('submit', 'add', array('label' => 'Aceptar'));
		
    	return $form;
	}
 	
	private function formatCategories($categories)
	{
		$options = array();
	
		foreach( $categories as $c )
		{
			$options[$c['id']] = $c['title'];
		}
		return $options;
	}
	
	public function editproductAction()
 	{
 		$form = $this->editProductForm();
 		$this->view->form = $form;	
   	    $langs = new Zend_Models_Lang();
 		$this->view->langs = $langs->getEnabledLangs();
 		if (!$this->getRequest()->isPost())
    	{
       		return;
     	}
    	 else
    	 {
    		if (!$form->isValid($_POST))
    	  	{
				$this->view->form = $form;
				return;
			}
			else
			{
			  $values = $form->getValues();
			  $product = new Zend_Models_Product();
			  $product = $product->getProductById($values['common']['product']);
			  $product->enabled = $values['common']['enabled'];
			  $product->hightlight = $values['common']['hightlight'];
			  $product->id_category = $values['common']['category'];
			  $product->price = $values['common']['price'];
			  if ( $values['common']['image'] == NULL )
			  {
				$product->image = $values['common']['imageHidden'];
			  }	
			  else
			  {
				$upload = $form->common->image->getTransferAdapter(); 
                $info = $upload->getFileInfo();
				if (!$upload->receive())
				{	
				  $messages = $upload->getMessages();
   			      echo implode("\n", $messages);
   				  exit;
				}	
				$product->image = $info['image']['name'];
			  }
			  $product->save();
			  $langs = new Zend_Models_Lang();
			  $langs = $langs->getEnabledLangs();
			  foreach( $langs as $l )
			  {
				$lc = new Zend_Models_LangProduct();
				$lc = $lc->getProductById($values['common']['product'], $l['prefix2']);
				if ( count( $lc ) <= 0 )
				  {
                    $lc = new Zend_Models_LangProduct();
				    $lc = $lc->createRow();
				  }  
				$lc->id_product = $product->id;
				$lc->lang = $l['prefix2'];
				$lc->title = $values[$l['prefix2']]['title_'.$l['prefix2']];
				$lc->description = $values[$l['prefix2']]['description_'.$l['prefix2']];
				$lc->save();
			  } 
			  $this->_redirect("/admin/product/listproducts/category/".$values['common']['category']);
			}
		}
 	}
 	/*
 	 * TODO : Imagen
 	 */
	private function editProductForm()
	{
    	$id_product = $this->_request->getParam('product');
    	$product = new Zend_Models_Product();         
        $product = $product->getProductById($id_product);
    	$form = new Zend_Form();
	 	$form->setAction("/admin/product/editproduct")
	             ->setMethod('post');
    	$form->setAttrib("class", "jNice");         
        $lang = Common_Translate::getLanguage();
        $common = new Zend_Form_SubForm(); 
    	$category = $form->createElement("select","category");
		$categories = new Zend_Models_LangProductCategory();
		$categories = $categories->getCategoriesByLang($lang);	
		$category->setLabel('Categoría:');
		$category->addMultiOptions($this->formatCategories($categories));
		$category->setValue($product->id_category); 
 	    $enabled = $common->createElement('checkbox','enabled');
 	    $enabled->setLabel('Activo:');
 	    $enabled->setValue($product->enabled);
 	    $hight = $common->createElement('checkbox','hightlight');
		$hight->setLabel('Destacado:');
		$hight->setValue($product->hightlight);
		$cost = $common->createElement('text','price');
		$cost->setAttrib("class", "text-long");
		$cost->addValidator('Float')->setLabel('*Precio:')->setRequired(true);
		$cost->addErrorMessage('Valor real invalido');
		$cost->setValue($product->price);
 	    $image =  new Zend_Form_Element_File('image');  
	    $image->addValidator('Extension', false, array('gif', 'jpg', 'png'))->addErrorMessage('Formato de imagen no valido');
	    $image->setDestination(str_replace("\\","/",dirname(dirname(dirname(dirname(dirname(__FILE__)))))).'/upload/producto/');
	    $imageHidden = $form->createElement('hidden', 'imageHidden');
	    $imageHidden->setLabel('Imagen:');	
		$imageHidden->setValue($product->image);
		$this->view->value = $product->image;
		$hidden = $common->createElement("hidden","product");
		$hidden->setValue($product->id);
		$common->addElement($category);
	    $common->addElement($enabled);
	    $common->addElement($hight);
	    $common->addElement($cost);
        $common->addElement($imageHidden);
	    $common->addElement($image);
	    $common->addElement($hidden);
	    $form->addSubForms(array("common" => $common));
        
	    $langs = new Zend_Models_Lang();
	    $langs = $langs->getEnabledLangs();
	    foreach( $langs as $l)
	    {
	      $sub = new Zend_Form_SubForm();
	      $pc = new Zend_Models_LangProduct();
	      $pc = $pc->getProductById($product->id, $l['prefix2']);
	      $name = $sub->createElement("text","title_".$l['prefix2']);
		  $name->setAttrib("class", "text-long");
 	   	  $name->addValidator('NotEmpty')->setLabel($this->view->t->_('*Titulo:'))->setRequired(true);
 	   	  $name->setValue($pc->title);
		  $name->addErrorMessage($this->view->t->_('Este_campo_es_obligatorio'));
		  $sub->addElement($name);
		  $description = $sub->createElement("textarea", "description_".$l['prefix2']);
		  $description->setAttrib("class","mceAdvanced");
		  $description->setLabel($this->view->t->_('Descripcion:'));
		  $description->setValue($pc->description);
		  $sub->addElement($description);
		  $form->addSubForms(array($l['prefix2'] => $sub));
	    }
   		$form->addElement('submit', 'add', array('label' => 'Aceptar'));
		
    	return $form;
 }
 	/*
 	 * TODO : Eliminar el file
 	 */
 	public function deleteproductAction()
	{
 		$this->disableView();
 		$request = $this->_request->getParams();
    	$product = $request['product']; 
   	 	$category = $request['category'];
   	 	$lp = new Zend_Models_LangProduct();
   	 	$lp->delete("id_product = '$product'");
   	 	$p = new Zend_Models_Product();
   	 	$p = $p->getProductById($product);
    	$p->delete();
    	$this->_redirect("/admin/product/listproducts/category/$category");
 	}
}    